package com.lc.projects.unit.thread.part02.test1;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//使用锁 实现同步
public class Test4 {
	public static void main(String[] args) {
		PrintQueue printQueue = new PrintQueue();
		Thread[] threads = new Thread[10];
		for (int i = 0; i < 10; i++) {
			threads[i] = new Thread(new Job(printQueue),"Thread "+i);
		}
		
		for (int i = 0; i < threads.length; i++) {
			threads[i].start();
		}
		
	}
}

class PrintQueue {
	private final Lock queueLock = new ReentrantLock();

	public void printJob(Object document) {
		queueLock.lock();

		try {
			Long duration = (long) (Math.random() * 10000);
			System.out.println(Thread.currentThread().getName() + " :PrintQueue: Printing a job during "
					+ (duration / 1000) + " secounds.");

			Thread.sleep(duration);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			queueLock.unlock();
		}

	}
}

class Job implements Runnable {
	private PrintQueue printQueue;

	public Job(PrintQueue printQueue) {
		super();
		this.printQueue = printQueue;
	}

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + " [start]");
		printQueue.printJob(new Object());
		System.out.println(Thread.currentThread().getName()+ " [end]");
	}

}